/*
 * @Author: blak-kong
 * @Date: 2019-12-10 12:57:42
 * @Email: 546598185@qq.com
 */


// models
const Recommend = require('../models/recommend');
const { SuccessModel, ErrorModel } = require("../models/resModel")


module.exports = {
    async uccn (ctx, next) {
        let recommendDocs = await Recommend.find({})
        let res = recommendDocs[0]


        let options = {
            skip: 0, // 跳过零
            limit: 3, // 取五条
            sort:{"create_time":"-1"}
        }
        let activityDocs = await News.find({category: "activity"}, null, options); // 活动
        let informationDocs = await News.find({category: "information"}, null, options); // 新闻
        let trendsDocs = await News.find({category: "trends"}, null, options); // 动态

        ctx.body = new SuccessModel({
            courses: res.courses,
            books: res.books,
            news: {
                activity: activityDocs,
                information: informationDocs,
                trends: trendsDocs
            }
        }, "请求成功!")
    },
    async query (ctx, next) {
        let docs = await Recommend.find({})
        if (docs.length > 0) {
            let res = docs[0]
            if (res.id) {
                ctx.body = new SuccessModel(res, "请求成功!")
                return
            }
            ctx.body = new ErrorModel({}, "服务器错误!")
        }
        ctx.body = new ErrorModel({}, "没有数据!")
    },
    
    async update (ctx, next) {
        // let markdowne = new Markdown(ctx.request.body)
        let docs = await Recommend.find({});
        let doc = docs[0]
         
        // 遍历对象/只更新传的值
        for(let i in ctx.request.body){
            if(ctx.request.body.hasOwnProperty(i)){
                doc[i] = ctx.request.body[i]
            }
        }
       
        let res = await doc.save()
        if (res.id) {
            ctx.body = new SuccessModel(res, "请求成功!")
            return
        }
        ctx.body = new ErrorModel({},"更新失败！请稍后重试！")
    },


    async add (ctx, next) {
        // save() 需要先给model赋值实例化
        let doc = new Recommend(ctx.request.body)
        let res = await doc.save()
        if (res.id) {
            ctx.body = new SuccessModel({}, "请求成功!")
            return
        }
        ctx.body = new ErrorModel({}, "创建失败！请稍后重试！")
    },
}